'use strict';

//读取配置文件，变量config的类型是Object类型
const config = require('./config');
// 用户获取签名的函数
const sign = require('./sign.js');
const db = uniCloud.database()
exports.main = async (event, context) => {
	//event为客户端上传的参数
	let params = event.params || {}
	params.redirect_uri = encodeURIComponent("https://vlog.minihack.cn")
	if (event.action === 'login') {
		// 授权获取用户信息
		var loginApiUrl =
			`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.appid}&redirect_uri=${params.redirect_uri}&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect`
		const res = await uniCloud.httpclient.request(loginApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		return res
	}
	if (event.action === 'getToken') {
		// 通过appid 和 AppSecret 获取token
		// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
		var apiUrl =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
		let res = await uniCloud.httpclient.request(apiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		let token = res.data.access_token
		return res
	}
	// 获取票据
	if (event.action === 'jsapi_ticket') {
		var tokenApiUrl =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
		// 获取token
		let getToken = await uniCloud.httpclient.request(tokenApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		let token = getToken.data.access_token
		// 获取Ticket
		var ticketApiUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
		let getTicket = await uniCloud.httpclient.request(ticketApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		let jsapi_ticket = getTicket.data.ticket
		return getTicket
	}

	// 生成签名
	if (event.action === 'signature') {
		// 1.获取ticket--
		let jsapi_ticket = ''
		// let cloudTicket = await db.collection('jsapi_ticket').orderBy("expires_in", "asc").limit(1).get()
		// // 查看jsapi_ticket是否过期
		// console.log('cloudTicket', cloudTicket)
		// console.log(parseInt(new Date().getTime() / 1000))
		// if (cloudTicket.data.length > 0 && parseInt(cloudTicket.data[0].expires_in) > parseInt(new Date().getTime() / 1000)) {
		// 	jsapi_ticket = cloudTicket.data[0].jsapi_ticket
		// } else {
		var tokenApiUrl =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
		// 获取token
		let getToken = await uniCloud.httpclient.request(tokenApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		let token = getToken.data.access_token
		// 获取Ticket
		var ticketApiUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
		let getTicket = await uniCloud.httpclient.request(ticketApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		// 拿到最新的票据
		jsapi_ticket = getTicket.data.ticket
		let expires_in = parseInt(new Date().getTime() / 1000) + parseInt(getTicket.data.expires_in)
		// 存到数据库
		await db.collection('jsapi_ticket').add({
			jsapi_ticket,
			expires_in
		})
		console.log('jsapi_ticket', getTicket.data)
		// }
		// 获取签名
		let signature = sign(jsapi_ticket, params.url)
		signature.appId = config.appid
		return signature
	}
	//返回数据给客户端
	return event
};

// async getToken(){
// 	let apiUrl=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
// 	const res = await uniCloud.httpclient.request(apiUrl, {
// 	    method: 'POST',	
// 	    data: {
// 	    },
// 	    dataType: 'json'
// 	  })
// 	  console.log(res)
// 	  return res
// }
// 通过appid 和 AppSecret 获取token 
// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
